# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: helpers\uploads\target_actions.py
import json, os, logging
from sqlalchemy import select as sql_select
from sqlalchemy import func as sql_func
from sqlalchemy import or_ as sql_or
from db import Connection
from db.tables.targets import TargetsTable, TargetRow
from db.tables.targets_configurations import (
    TargetConfigurationRow,
    TargetConfigurationTable,
)
from db.tables.uploads import UploadRow, UploadsTable
from settings_provider import settings
from helpers.setup_types import *
from server.http_responses.http_errors import Http409
from helpers.hashing import sha256

_logger = logging.getLogger("helpers.uploads.target_actions")


class TargetUploadActionHandler:
    def __init__(self, shard, file_storage):
        self.shard_name = shard
        self.file_storage = file_storage

    def on_lsr_uploaded(self, target_id, upload_descriptor):
        upload_id = upload_descriptor["upload_id"]
        sf = upload_descriptor["destination"]
        try:
            ls = (open(sf, "rt", encoding="utf-8")).read()
            ls = json.loads(ls)
        except ValueError:
            try:
                os.remove(upload_descriptor["destination"])
            except Exception:
                pass

            raise Http409("invalid LSR format")
        except Exception:
            try:
                os.remove(upload_descriptor["destination"])
            except Exception:
                pass

            raise Http409("invalid LSR format")

        manual_intervention = False
        for action in ls.get("actions", []):
            if action["type"] == "manual":
                manual_intervention = True
                break

        if settings["setup_type"] == AWS:
            if manual_intervention:
                try:
                    os.remove(upload_descriptor["destination"])
                except Exception:
                    pass

                raise Http409("login sequence with manual intervention not supported")
        t_lc_q = (
            sql_select((TargetConfigurationRow.value,))
            .where(TargetConfigurationRow.target_id == target_id)
            .where(TargetConfigurationRow.name == "login_sequence")
        )
        u_mi_q = (UploadsTable.update(values=dict(data=dict(mi=True)))).where(
            UploadRow.upload_id == upload_id
        )
        with Connection(self.shard_name) as (db):
            if manual_intervention:
                db.execute(u_mi_q)
            previous_ls = db.execute(t_lc_q).fetchone()
            if previous_ls:
                q = (
                    (
                        TargetConfigurationTable.update(
                            values=dict(value=dict(upload_id=str(upload_id)))
                        )
                    )
                    .where(TargetConfigurationRow.target_id == target_id)
                    .where(TargetConfigurationRow.name == "login_sequence")
                )
                db.execute(q)
                q = (
                    UploadsTable.update(
                        values=dict(deleted_at=sql_func.current_timestamp())
                    )
                ).where(UploadRow.upload_id == previous_ls.value["upload_id"])
                db.execute(q)
                t_lk_q = (
                    sql_select((TargetConfigurationRow.value,))
                    .where(TargetConfigurationRow.target_id == target_id)
                    .where(TargetConfigurationRow.name == "login")
                )
                login_kind = db.execute(t_lk_q).fetchone()
                if login_kind:
                    if login_kind.value["kind"] == "sequence":
                        qt = (
                            (
                                TargetsTable.update(
                                    values=dict(manual_intervention=manual_intervention)
                                )
                            )
                            .where(TargetRow.target_id == target_id)
                            .where(
                                sql_or(
                                    TargetRow.manual_intervention
                                    != manual_intervention,
                                    TargetRow.manual_intervention.is_(None),
                                )
                            )
                        )
                        db.execute(qt)
                if is_setup_type(AWS):
                    from helpers.aws.s3 import delete_file as aws_delete_file

                    ext = ".lsr"
                    destination = "%s/%s/%s" % (
                        settings["storage.targets.s3.dir"],
                        upload_descriptor["owner_id"],
                        previous_ls.value["upload_id"] + ext,
                    )
                    settings["rq_s3_uploads"].enqueue(
                        aws_delete_file,
                        settings["storage.targets.s3.bucket"],
                        destination,
                    )
                else:
                    if is_setup_type(ON_PREMISE_MASTER):
                        pl = os.path.join(
                            self.file_storage, previous_ls.value["upload_id"]
                        )
                        try:
                            os.remove(pl)
                        except Exception as e:
                            _logger.exception(
                                "delete previous lsr %s failed with %s", pl, e
                            )

                    else:
                        q = TargetConfigurationTable.insert().values(
                            target_id=target_id,
                            name="login_sequence",
                            value=dict(upload_id=str(upload_id)),
                        )
                        db.execute(q)
